from datetime import datetime

from werkzeug.security import generate_password_hash, check_password_hash # type: ignore

from flask_shop import db

class BaseModel(object):  
    create_time = db.Column(db.DateTime, default=datetime.now)
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)


class User(db.Model,BaseModel):
    __tablename__ = 't_users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(32), unique=True,nullable=False)
    pwd = db.Column(db.String(128))
    nick_name = db.Column(db.String(32))
    phone = db.Column(db.String(11))
    email = db.Column(db.String(32))
    
    # 建立用户与角色的关系多对1
    role_id = db.Column(db.Integer, db.ForeignKey('t_roles.id'))
    @property
    def password(self):
        return self.pwd

    @password.setter
    def password(self, pwd):
        # 数据密码数据加密
        self.pwd = generate_password_hash(pwd)

    def check_password(self, pwd):
        # 检查密码是否正确
        return check_password_hash(self.pwd, pwd)
    
    def to_dict(self):
        return {
            'id':self.id,
            'name':self.name,
            'nick_name':self.nick_name,
            'phone':self.phone,
            'email':self.email,
            'role_name':self.role.name,
        }
    
trm = db.Table(
    't_roles_menus',
    db.Column('role_id',db.Integer,db.ForeignKey('t_roles.id')),
    db.Column('menu_id',db.Integer,db.ForeignKey('t_menus.id')),
              
)

class Menu(db.Model,BaseModel):
    __tablename__ = 't_menu'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(32), unique=True,nullable=False)
    level = db.Column(db.Integer, default=1)
    path = db.Column(db.String(32))

    pid = db.Column(db.Integer, default=-1)
    children = db.relationship('Menu')
    roles = db.relationship('Role',secondary=trm,backref='menus')


    def to_dict_tree(self):
        return {
        'id': self.id,
        'name': self.name,
        'level': self.level,
        'path': self.path,
        'pid': self.pid,
        'children': [child.to_dict_tree() for child in self.children]
        }
    def to_dict_list(self):
        return {
            'id': self.id,
            'name': self.name,
            'path': self.path,
            'level': self.level,
            'pid': self.pid,
     }
    
class Role(db.Model):
    __tablename__='t_roles'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(32),unique=True,nullable=False)
    desc = db.Column(db.String(128))

    # 建立角色与用户的关系1对多
    users = db.relationship('User', backref='role')
    #menus = db.relationship('Menus',secondary=trm)
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'desc': self.desc,
            #'menus':[m.to_dict_list() for m in self.menus]
            #'menus':[m.to_dict_tree() for m in self.menus if m.level ==1]
            'menus':self.get_menu_dict()
            }
    def get_menu_dict(self):
        #创建一列表存储所有的菜单
        menu_list = []
        menus =sorted(self.menus,key=lambda temp:temp.id)
        #查询所有的一级菜单
        for m in self.menus:
            #判断是否是一级菜单
            if m.level == 1:
                first_dict = m.to_dict_list()
                #查询所有的二级菜单
                first_dict['children']=[]
                for m2 in self.menus:
                    #判断是否是二级菜单，且二级菜单的pif是否等于一级菜单的id
                    if m2.level == 2 and m2.pid == m.id:
                        #将二级菜单添加到一级菜单的children中
                        first_dict['children'].append(m2.to_dict_list())
                #将一级菜单添加到列表中
                menu_list.append(first_dict)
        return menu_list 
class Category(db.Model):
    __tablename__ = 't-category'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(32), nullable=False)
    level = db.Column(db.Integer, default=1)
    pid = db.Column(db.Integer, db.ForeignKey('t_category.id'))

    children = db.relationship('Category')

    def to_dict(self):
        return{
            'id': self.id,
            'name': self.name,
            'level': self.level,
            'pid': self.pid,
        }